package com.company.oa.hr.controller.training;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.company.oa.common.api.Result;
import com.company.oa.hr.dto.training.PlanDTO;
import com.company.oa.hr.entity.training.Plan;
import com.company.oa.hr.service.training.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/hr/training/plan")
public class PlanController {

    @Autowired
    private PlanService planService;

    /**
     * 分页查询培训计划列表
     */
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('hr:training:plan:list')")
    public Result<IPage<Plan>> getPlanPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            Plan plan) {
        IPage<Plan> pageResult = planService.getPlanPage(page, size, plan);
        return Result.success(pageResult);
    }

    /**
     * 获取培训计划详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('hr:training:plan:info')")
    public Result<Plan> getPlanDetail(@PathVariable Long id) {
        Plan plan = planService.getById(id);
        return Result.success(plan);
    }

    /**
     * 创建培训计划
     */
    @PostMapping
    @PreAuthorize("hasAuthority('hr:training:plan:create')")
    public Result<Boolean> createPlan(@RequestBody @Valid PlanDTO planDTO) {
        // 从当前登录用户中获取创建人ID
        Long creatorId = 1L; // 实际项目中应从SecurityContext中获取
        boolean success = planService.createPlan(planDTO, creatorId);
        return Result.success(success);
    }

    /**
     * 更新培训计划
     */
    @PutMapping
    @PreAuthorize("hasAuthority('hr:training:plan:update')")
    public Result<Boolean> updatePlan(@RequestBody @Valid PlanDTO planDTO) {
        boolean success = planService.updatePlan(planDTO);
        return Result.success(success);
    }

    /**
     * 删除培训计划
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('hr:training:plan:delete')")
    public Result<Boolean> deletePlan(@PathVariable Long id) {
        boolean success = planService.deletePlan(id);
        return Result.success(success);
    }

    /**
     * 发布培训计划
     */
    @PostMapping("/publish/{id}")
    @PreAuthorize("hasAuthority('hr:training:plan:publish')")
    public Result<Boolean> publishPlan(@PathVariable Long id) {
        boolean success = planService.publishPlan(id);
        return Result.success(success);
    }

    /**
     * 取消培训计划
     */
    @PostMapping("/cancel/{id}")
    @PreAuthorize("hasAuthority('hr:training:plan:cancel')")
    public Result<Boolean> cancelPlan(@PathVariable Long id) {
        boolean success = planService.cancelPlan(id);
        return Result.success(success);
    }
}